﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Serviio.API;

namespace Serviio.WHS2011
{
    public partial class AdvancedTabControl : UserControl
    {
        private static readonly LogFacade log = LogFacade.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public AdvancedTabControl()
        {
            InitializeComponent();
        }

        private ServiioConnection conn = null;

        public void Initialize(ServiioConnection connection)
        {
            try
            {
                if (this.conn != null)
                    return;

                log.Info("Initializing...");

                this.conn = connection;

                if (!conn.CheckMinVersion("0.6.1"))
                    checkBoxBestVideoQuality.Visible = false;

                comboBoxMetadataSource.DataSource = new BindingSource(connection.Reference.DescriptiveMetadataExtractors, null);
                comboBoxMetadataSource.DisplayMember = "Value";
                comboBoxMetadataSource.ValueMember = "Key";

                comboBoxPreferredLanguage.DataSource = new BindingSource(connection.Reference.MetadataLanguages, null);
                comboBoxPreferredLanguage.DisplayMember = "Value";
                comboBoxPreferredLanguage.ValueMember = "Key";

                comboBoxCpus.DataSource = new BindingSource(connection.Reference.CpuCores, null);
                comboBoxCpus.DisplayMember = "Value";
                comboBoxCpus.ValueMember = "Value";

                PopulateMetadata();
                PopulateTranscoding();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void PopulateMetadata()
        {
            try
            {
                checkboxLocalThumbs.Checked = conn.Metadata.VideoGenerateLocalThumbnailEnabled;
                checkboxLocalCoverImage.Checked = conn.Metadata.VideoLocalArtExtractorEnabled;
                checkboxOnlineImage.Checked = conn.Metadata.VideoOnlineArtExtractorEnabled;
                checkboxLocalAlbumArt.Checked = conn.Metadata.AudioLocalArtExtractorEnabled;
                comboBoxMetadataSource.SelectedValue = conn.Metadata.DescriptiveMetadataExtractor;
                comboBoxPreferredLanguage.SelectedValue = conn.Metadata.MetadataLanguage;
                checkboxOriginalTitla.Checked = conn.Metadata.RetrieveOriginalTitle;

                if ("ONLINE_VIDEO_SOURCES".Equals(conn.Metadata.DescriptiveMetadataExtractor))
                    checkboxOnlineImage.Enabled = true;
                else
                    checkboxOnlineImage.Enabled = false;

                buttonSaveMetadata.Enabled = false;
                buttonCancelMetadata.Enabled = false;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void PopulateTranscoding()
        {
            try
            {
                checkBoxEnableTranscoding.Checked = conn.Transcoding.TranscodingEnabled;
                textBoxFolderPath.Text = conn.Transcoding.TranscodingFolderLocation;
                comboBoxCpus.SelectedValue = conn.Transcoding.NumberOfThreads.ToString();
                checkBoxAudioDownmixing.Checked = conn.Transcoding.AudioDownmixing;
                checkBoxBestVideoQuality.Checked = conn.Transcoding.BestVideoQuality;

                buttonSaveTranscoding.Enabled = false;
                buttonCancelTranscoding.Enabled = false;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void metadataItemChanged(object sender, EventArgs e)
        {
            try
            {
                buttonSaveMetadata.Enabled = true;
                buttonCancelMetadata.Enabled = true;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void comboBoxMetadataSource_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                metadataItemChanged(sender, e);

                if ("ONLINE_VIDEO_SOURCES".Equals(comboBoxMetadataSource.SelectedValue.ToString()))
                    checkboxOnlineImage.Enabled = true;
                else
                    checkboxOnlineImage.Enabled = false;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void buttonSaveMetadata_Click(object sender, EventArgs e)
        {
            try
            {
                conn.Metadata.VideoGenerateLocalThumbnailEnabled = checkboxLocalThumbs.Checked;
                conn.Metadata.VideoLocalArtExtractorEnabled = checkboxLocalCoverImage.Checked;
                conn.Metadata.VideoOnlineArtExtractorEnabled = checkboxOnlineImage.Checked;
                conn.Metadata.AudioLocalArtExtractorEnabled = checkboxLocalAlbumArt.Checked;
                conn.Metadata.DescriptiveMetadataExtractor = comboBoxMetadataSource.SelectedValue.ToString();
                conn.Metadata.MetadataLanguage = comboBoxPreferredLanguage.SelectedValue.ToString();
                conn.Metadata.RetrieveOriginalTitle = checkboxOriginalTitla.Checked;
                if (!conn.Metadata.Update())
                    MessageBox.Show("There was an error updating the Metadata info", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                conn.Metadata.Refresh();
            }
            PopulateMetadata();
        }

        private void buttonCancelMetadata_Click(object sender, EventArgs e)
        {
            PopulateMetadata();
        }

        private void transcodingItemChanged(object sender, EventArgs e)
        {
            try
            {
                buttonSaveTranscoding.Enabled = true;
                buttonCancelTranscoding.Enabled = true;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void checkBoxEnableTranscoding_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                transcodingItemChanged(sender, e);

                groupBoxTranscodingGeneral.Enabled = checkBoxEnableTranscoding.Checked;
                groupBoxTranscodingVideo.Enabled = checkBoxEnableTranscoding.Checked;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            try
            {
                folderBrowserDialog1.Description = "Select a folder to use for temporary transcoded media files.";
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    textBoxFolderPath.Text = folderBrowserDialog1.SelectedPath;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void buttonSaveTranscoding_Click(object sender, EventArgs e)
        {
            try
            {
                conn.Transcoding.TranscodingEnabled = checkBoxEnableTranscoding.Checked;
                conn.Transcoding.TranscodingFolderLocation = textBoxFolderPath.Text;
                conn.Transcoding.NumberOfThreads = Int32.Parse(comboBoxCpus.SelectedValue.ToString());
                conn.Transcoding.AudioDownmixing = checkBoxAudioDownmixing.Checked;
                conn.Transcoding.BestVideoQuality = checkBoxBestVideoQuality.Checked;
                if (!conn.Transcoding.Update())
                    MessageBox.Show("There was an error updating the Transcoding info", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                conn.Metadata.Refresh();
            }
            PopulateTranscoding();
        }

        private void buttonCancelTranscoding_Click(object sender, EventArgs e)
        {
            PopulateTranscoding();
        }

        private void buttonForceVideoFilesMetadataUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                conn.ForceVideoFilesMetadataUpdate();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void panelLeftColumn_Paint(object sender, PaintEventArgs e)
        {
            GuiHelper.DrawBorder(e, panelLeftColumn, new GuiHelper.BorderSides(true, true, false, false));
        }

        private void linkServiceAccount_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                ChangeServiceAccountForm dialog = new ChangeServiceAccountForm();
                dialog.ChangeServiceLogin(conn);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void linkViewLog_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                User32Helper.StartChildProcess(this.ParentForm, "notepad.exe", conn.ServiceFilePath + "\\..\\log\\serviio.log", true, false);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void linkLogConfigFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                User32Helper.StartChildProcess(this.ParentForm, "notepad.exe", conn.ServiceFilePath + "\\..\\config\\log4j.xml", true, false);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void linkProfilesFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                User32Helper.StartChildProcess(this.ParentForm, "notepad.exe", conn.ServiceFilePath + "\\..\\config\\profiles.xml", true, false);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void linkManagedServer_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                ChangeServerAddressForm dialog = new ChangeServerAddressForm();
                if (dialog.ChangeServerAddress())
                    MessageBox.Show("You must restart the Dashboard for any changes to take effect.");
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

    }
}
